<script setup lang="ts">
// 这个接口获取付款信息 折扣信息
import {
  createConsultOrder,
  getConsultOrderPre,
  getPatientDetail
} from '@/services/consult'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog } from 'vant'
import { onMounted, ref } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'

const store = useConsultStore()

// 定义一个函数 加载付款信息
const payInfo = ref<ConsultOrderPreData>()
const load = async () => {
  const res = await getConsultOrderPre({
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  payInfo.value = res.data
}

// 定义一个函数 加载患者信息
const patient = ref<Patient>()
const loadPatient = async () => {
  if (!store.consult.patientId) return

  const res = await getPatientDetail(store.consult.patientId)
  patient.value = res.data
}

onMounted(() => {
  load()
  loadPatient()
})

// --------------点击立即支付----------------------------------------
const agree = ref(true)

const orderId = ref<string>()
const submit = async () => {
  if (!agree.value) return
  console.log('可以进入支付流程了')
  // 1. 创建订单 => 调用接口(把你收集的一堆问诊信息传给后端 => 生成一笔订单 id)
  const res = await createConsultOrder(store.consult)
  orderId.value = res.data.id
  // store.clear() // 清除仓库中收集好的信息
  show.value = true // 打开支付方式的选择
}

// --------------选择支付方式----------------------------------------
const show = ref(false)

// ------进入到动作面板选择支付方式了 那么订单已经创建了 => 限制用户返回----
// 路由钩子 => 检测页面是否离开
onBeforeRouteLeave(() => {
  // console.log(111)
  // return false // 阻止路由跳转
  if (orderId.value) return false
})

// 一旦点击actionsheet蒙层 就会触发beforeclose配置的函数
const router = useRouter()
const fn = () => {
  // return false // 阻止关闭
  // return true // 继续关闭

  // console.log(111)
  // 打算给一个确认框 主动确认取消
  return showConfirmDialog({
    title: '提示',
    message: '你确定取消支付么?',
    confirmButtonText: '狠心离开',
    cancelButtonText: '继续支付'
  })
    .then(() => {
      // console.log('确认')
      // 狠心离开 => 跳转列表页面/user/consult+继续关闭
      orderId.value = '' // 能够保证页面跳转
      router.push('/user/consult') // 可以在这个列表页面找到那笔待支付的的订单 继续完成支付
      return true
    })
    .catch(() => {
      console.log('取消')
      return false
    })
}
</script>

<template>
  <div class="consult-pay-page" v-if="payInfo && patient">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell
        title="实付款"
        :value="`¥${payInfo.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient.name} | ${patient.genderValue} | ${patient.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">
        我已同意 <span class="text">支付协议</span>
      </van-checkbox>
    </div>
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="submit"
    />
    <!-- 
      确认框 默认会在返回时自动关闭
      action-sheet 默认会在返回时自动关闭
        :close-on-popstate="false"  回退时 不会自动关闭

        :closeable="false"  不显示关闭图标

        :before-close="fn"  配置关闭之前的逻辑
     -->
    <!-- :show="show" @update:show="..." -->
    <CpPaySheet
      v-model:show="show"
      :orderId="orderId"
      :onClose="fn"
      :actualPayment="payInfo.actualPayment"
    ></CpPaySheet>
    <!-- <van-action-sheet
      v-model:show="show"
      title="选择支付方式"
      :close-on-popstate="false"
      :closeable="false"
      :before-close="fn"
    >
      <div class="pay-type">
        <p class="amount">￥20.00</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra>
              <van-checkbox :checked="paymentMethod === 0" />
            </template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra>
              <van-checkbox :checked="paymentMethod === 1" />
            </template>
          </van-cell>
        </van-cell-group>

        <div class="btn">
          <van-button @click="getUrl" type="primary" round block>
            立即支付
          </van-button>
        </div>
      </div>
    </van-action-sheet> -->
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
